package top.glkj.hms.security;

import org.springframework.security.core.Authentication;
import top.glkj.hms.entity.Permission;
import top.glkj.hms.entity.Role;
import top.glkj.hms.entity.User;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/11/28 1:52
 */
public class UserPermissionEvaluator implements org.springframework.security.access.PermissionEvaluator {
    /**
     * @param authentication     represents the user in question. Should not be null.
     * @param targetDomainObject the domain object for which permissions should be
     *                           checked. May be null in which case implementations should return false, as the null
     *                           condition can be checked explicitly in the expression.
     * @param permission         a representation of the permission object as supplied by the
     *                           expression system. Not null.
     * @return true if the permission is granted, false otherwise
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        User principal = (User) authentication.getPrincipal();
        Set<String> set = new HashSet<>();
        for (Role role : principal.getRoles()) {
            for (Permission p : role.getPermissions()) {
                set.add(p.getPermissionCode());
            }
        }
        // 权限对比
        if (set.contains(permission.toString())) {
            return true;
        }
        return false;
    }

    /**
     * Alternative method for evaluating a permission where only the identifier of the
     * target object is available, rather than the target instance itself.
     *
     * @param authentication represents the user in question. Should not be null.
     * @param targetId       the identifier for the object instance (usually a Long)
     * @param targetType     a String representing the target's type (usually a Java
     *                       classname). Not null.
     * @param permission     a representation of the permission object as supplied by the
     *                       expression system. Not null.
     * @return true if the permission is granted, false otherwise
     */
    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
